import { useState, useEffect } from 'react';
import { useAuth } from '@/hooks/use-auth';

// 全局临时参数数据存储
const tempParameterData = new Map<string, Record<number, string>>();

// 生成存储键，包含设备类型以增强隔离
const getTempDataKey = (instanceId: number, tableName: string, deviceTypeCode?: string) => 
  deviceTypeCode ? `${instanceId}-${tableName}-${deviceTypeCode}` : `${instanceId}-${tableName}`;

export interface ParameterField {
  id: number;
  field_name: string;
  field_description: string;
  data_type: string;
  measurement_unit: string;
  measurement_class: string;
  data_source: string;
  example_description: string;
  is_required: boolean;
  parameter_value?: string;
}

export interface FilteredParameterField extends ParameterField {
  canEdit: boolean;
  isVisible: boolean;
}

export function useDeviceInstanceParameters(tableName: string, instanceId?: number, deviceTypeCode?: string) {
  const [fields, setFields] = useState<FilteredParameterField[]>([]);
  const [allFields, setAllFields] = useState<FilteredParameterField[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [editData, setEditData] = useState<Record<number, string>>({});
  
  // 获取用户权限信息
  const { user, permissions, canEditField, hasDataSourceAccess } = useAuth(tableName);
  

  useEffect(() => {
    console.log('=== useEffect 触发条件检查 ===');
    console.log('tableName:', tableName);
    console.log('instanceId:', instanceId);
    console.log('user:', user);
    console.log('permissions:', permissions);
    console.log('是否满足加载条件:', !!(tableName && instanceId && user && permissions));
    
    if (tableName && instanceId && user && permissions) {
      loadParameterFields();
    } else {
      console.log('不满足加载条件，等待数据...');
    }
  }, [tableName, instanceId, user, permissions]);

  const loadParameterFields = async () => {
    try {
      setLoading(true);
      setError(null);

      console.log('=== 开始加载参数字段 ===');
      console.log('表名:', tableName);
      console.log('实例ID:', instanceId);
      console.log('用户:', user);
      console.log('权限:', permissions);

      // 获取字段元数据
      const metadataUrl = `/api/field-metadata?tableName=${tableName}`;
      console.log('请求字段元数据:', metadataUrl);

      const metadataResponse = await fetch(metadataUrl);
      const metadataData = await metadataResponse.json();

      console.log('字段元数据响应:', metadataData);

      if (!metadataData.success) {
        throw new Error(metadataData.error || '获取字段元数据失败');
      }

      // 获取设备实例参数数据
      let parameterData: any = {};
      if (instanceId) {
        const parameterUrl = `/api/device-instance-parameters?instanceId=${instanceId}&tableName=${tableName}`;
        console.log('请求设备实例参数:', parameterUrl);

        const parameterResponse = await fetch(parameterUrl);
        const parameterResult = await parameterResponse.json();

        console.log('设备实例参数响应:', parameterResult);

        if (parameterResult.success && parameterResult.data && parameterResult.data.parameters) {
          parameterData = parameterResult.data.parameters;
        }
      }

      // 处理字段权限和可见性
      const fieldsArray = metadataData.data.fields || [];
      console.log('原始字段数组:', fieldsArray);
      console.log('字段数量:', fieldsArray.length);

      const processedFields: FilteredParameterField[] = fieldsArray.map((field: ParameterField) => {
        // 所有字段都可见
        const isVisible = true;

        // 编辑权限基于用户角色和字段的数据来源
        const canEdit = (() => {
          if (!user || !permissions) {
            return false;
          }

          // 管理员可以编辑所有字段
          if (permissions.canEditAll) {
            return true;
          }

          // 查看角色不能编辑任何字段
          if (user.role_code === 'V') {
            return false;
          }

          // 其他角色只能编辑对应数据来源的字段
          const hasAccess = permissions.dataSourceAccess && permissions.dataSourceAccess.includes(field.data_source);
          return hasAccess;
        })();

        // 直接使用原始字段名，不进行数组处理
        console.log(`处理字段 ${field.field_name}:`, {
          data_source: field.data_source,
          canEdit,
          isVisible,
          parameter_value: parameterData[field.field_name] || ''
        });

        return {
          ...field,
          field_name: field.field_name,
          parameter_value: parameterData[field.field_name] || '',
          canEdit,
          isVisible
        };
      });

      // 显示所有可见字段，权限控制在编辑层面
      const filteredFields = processedFields.filter(field => field.isVisible);
      console.log('过滤后的可见字段:', filteredFields);
      console.log('可见字段数量:', filteredFields.length);

      // 按照权限排序：可编辑字段排在前面
      const sortedFields = filteredFields.sort((a, b) => {
        if (a.canEdit !== b.canEdit) {
          return a.canEdit ? -1 : 1;
        }
        return a.field_sequence - b.field_sequence;
      });
      console.log('排序后的字段:', sortedFields);
      console.log('可编辑字段数量:', sortedFields.filter(f => f.canEdit).length);

      setAllFields(processedFields);
      setFields(sortedFields);

      // 初始化编辑数据
      const initialEditData: Record<number, string> = {};
      processedFields.forEach(field => {
        if (field.parameter_value) {
          initialEditData[field.id] = field.parameter_value;
        }
      });
      
      // 如果有临时保存的数据，合并到初始数据中
      const tempKey = getTempDataKey(instanceId!, tableName, deviceTypeCode);
      let tempData = tempParameterData.get(tempKey);
      
      // 如果内存中没有数据，尝试从localStorage恢复
      if (!tempData) {
        try {
          const storageKey = deviceTypeCode ? `tempParams_${instanceId}_${deviceTypeCode}` : `tempParams_${instanceId}`;
          const storedData = localStorage.getItem(storageKey);
          if (storedData) {
            const parsedData = JSON.parse(storedData);
            tempData = parsedData[tempKey];
            if (tempData) {
              tempParameterData.set(tempKey, tempData);
              console.log('从localStorage恢复临时数据:', tempKey, tempData);
            }
          }
        } catch (error) {
          console.error('从localStorage恢复数据失败:', error);
        }
      }
      
      if (tempData) {
        console.log('恢复临时保存的数据:', tempData);
        Object.assign(initialEditData, tempData);
      }
      
      setEditData(initialEditData);

    } catch (error) {
      console.error('加载设备实例参数字段失败:', error);
      setError(error instanceof Error ? error.message : '加载设备实例参数字段失败');
    } finally {
      setLoading(false);
    }
  };

  const updateFieldValue = (fieldId: number, value: string) => {
    setEditData(prev => {
      const newData = {
        ...prev,
        [fieldId]: value
      };
      
      // 实时保存到临时存储中
      if (instanceId && tableName) {
        const tempKey = getTempDataKey(instanceId, tableName, deviceTypeCode);
        tempParameterData.set(tempKey, newData);
        
        // 同时保存到localStorage作为持久化存储
        try {
          const storageKey = deviceTypeCode ? `tempParams_${instanceId}_${deviceTypeCode}` : `tempParams_${instanceId}`;
          const existingData = JSON.parse(localStorage.getItem(storageKey) || '{}');
          existingData[tempKey] = newData;
          localStorage.setItem(storageKey, JSON.stringify(existingData));
          console.log('实时保存临时数据到内存和localStorage:', tempKey, newData);
        } catch (error) {
          console.error('保存到localStorage失败:', error);
        }
      }
      
      return newData;
    });
  };

  const saveParameters = async (): Promise<{ success: boolean; missingFields?: string[] }> => {
    if (!instanceId) {
      throw new Error('设备实例ID不能为空');
    }

    try {
      // 只保存用户有权限编辑的字段
      const editableFields = fields.filter(field => field.canEdit);
      
      // 检查必填字段是否已填写
      const missingRequiredFields: string[] = [];
      const dataToSave: Record<string, string> = {};
      
      editableFields.forEach(field => {
        const value = editData[field.id];
        const trimmedValue = value?.trim() || '';
        
        // 检查必填字段
        if (Boolean(field.is_required) && !trimmedValue) {
          missingRequiredFields.push(field.field_name);
        }
        
        if (value !== undefined) {
          dataToSave[field.field_name] = value;
        }
      });
      
      // 如果有未填写的必填字段，记录警告但允许保存
      if (missingRequiredFields.length > 0) {
        console.warn(`以下必填字段尚未填写：${missingRequiredFields.join('、')}，已保存当前数据`);
      }

      // 检查是否为临时设备实例（新建设备或临时ID）
      if (instanceId === 999 || instanceId <= 0) {
        console.log('临时设备实例，仅保存到前端状态');
        // 确保临时数据已保存
        const tempKey = getTempDataKey(instanceId, tableName, deviceTypeCode);
        tempParameterData.set(tempKey, editData);
        
        // 同时保存到localStorage
        try {
          const storageKey = deviceTypeCode ? `tempParams_${instanceId}_${deviceTypeCode}` : `tempParams_${instanceId}`;
          const existingData = JSON.parse(localStorage.getItem(storageKey) || '{}');
          existingData[tempKey] = editData;
          localStorage.setItem(storageKey, JSON.stringify(existingData));
          console.log('临时保存参数数据到内存和localStorage:', tempKey, editData);
        } catch (error) {
          console.error('保存到localStorage失败:', error);
        }
        
        // 对于临时设备实例，仅返回成功状态，不调用API
        return {
          success: true,
          message: '参数已临时保存，将在设备实例保存时一并提交',
          data: { parameters: dataToSave },
          missingFields: missingRequiredFields.length > 0 ? missingRequiredFields : undefined
        };
      }

      // 对于已存在的设备实例，调用API保存
      const response = await fetch('/api/device-instance-parameters', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          instanceId,
          tableName,
          data: dataToSave
        }),
      });

      const result = await response.json();
      
      if (!result.success) {
        throw new Error(result.error || '保存参数失败');
      }

      // API保存成功后，也更新临时存储，确保数据持久化
      const tempKey = getTempDataKey(instanceId, tableName, deviceTypeCode);
      tempParameterData.set(tempKey, editData);
      console.log('API保存成功，更新临时数据:', tempKey, editData);

      return {
        ...result,
        missingFields: missingRequiredFields.length > 0 ? missingRequiredFields : undefined
      };
    } catch (error) {
      console.error('保存设备实例参数失败:', error);
      throw error;
    }
  };

  const getFieldsByDataSource = (dataSource: string) => {
    const result = allFields.filter(field => field.data_source === dataSource);
    console.log(`getFieldsByDataSource(${dataSource}): 从 ${allFields.length} 个字段中找到 ${result.length} 个字段`)
    return result;
  };

  const getEditableFieldsCount = () => {
    return fields.filter(field => field.canEdit).length;
  };

  const getVisibleFieldsCount = () => {
    return fields.filter(field => field.isVisible).length;
  };

  const getUserDataSources = () => {
    const sources = new Set(fields.map(field => field.data_source));
    return Array.from(sources).filter(source => hasDataSourceAccess(source));
  };

  const getRequiredFieldsCount = () => {
    return fields.filter(field => field.canEdit && Boolean(field.is_required)).length;
  };

  const getFilledRequiredFieldsCount = () => {
    return fields.filter(field => {
      if (!field.canEdit || !Boolean(field.is_required)) return false;
      const value = editData[field.id]?.trim() || '';
      return value.length > 0;
    }).length;
  };

  const getMissingRequiredFields = () => {
    return fields.filter(field => {
      if (!field.canEdit || !Boolean(field.is_required)) return false;
      const value = editData[field.id]?.trim() || '';
      return value.length === 0;
    });
  };

  // 清理临时数据（当设备实例保存后调用）
  const clearTempData = (instanceId: number) => {
    // 清理所有与该实例相关的临时数据
    const keysToDelete: string[] = [];
    tempParameterData.forEach((_, key) => {
      if (key.startsWith(`${instanceId}-`)) {
        keysToDelete.push(key);
      }
    });
    
    keysToDelete.forEach(key => {
      tempParameterData.delete(key);
      console.log('清理临时数据:', key);
    });
  };

  // 获取临时数据（用于设备实例保存时获取所有参数）
  const getTempDataForInstance = (instanceId: number) => {
    const result: Record<string, Record<string, string>> = {};
    tempParameterData.forEach((data, key) => {
      if (key.startsWith(`${instanceId}-`)) {
        const tableName = key.split('-')[1];
        if (tableName) {
          // 将字段ID映射转换为字段名映射
          const fieldData: Record<string, string> = {};
          Object.entries(data).forEach(([fieldId, value]) => {
            const field = allFields.find(f => f.id === parseInt(fieldId));
            if (field && value.trim()) {
              fieldData[field.field_name] = value;
            }
          });
          if (Object.keys(fieldData).length > 0) {
            result[tableName] = fieldData;
          }
        }
      }
    });
    return result;
  };

  return {
    fields,
    loading,
    error,
    editData,
    user,
    permissions,
    updateFieldValue,
    saveParameters,
    loadParameterFields,
    getFieldsByDataSource,
    getEditableFieldsCount,
    getVisibleFieldsCount,
    getUserDataSources,
    getRequiredFieldsCount,
    getFilledRequiredFieldsCount,
    getMissingRequiredFields,
    canEditField,
    hasDataSourceAccess,
    clearTempData,
    getTempDataForInstance
  };
}